package com.yami.shop.api.controller;


import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yami.shop.api.config.SpringConfig;
import com.yami.shop.bean.model.User;
import com.yami.shop.bean.param.UserRegisterParam;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.util.PrincipalUtil;
import com.yami.shop.common.util.RedisUtil;
import com.yami.shop.otherservice.SendSmsService;
import com.yami.shop.security.common.bo.UserInfoInTokenBO;
import com.yami.shop.security.common.enums.SysTypeEnum;
import com.yami.shop.security.common.manager.PasswordManager;
import com.yami.shop.security.common.manager.TokenStore;
import com.yami.shop.security.common.vo.TokenInfoVO;
import com.yami.shop.service.UserService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import jodd.util.StringUtil;
import lombok.AllArgsConstructor;
import com.yami.shop.common.response.ServerResponseEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户信息
 *
 * @author SJL
 */
@RestController
@RequestMapping("/user")
@Tag(name = "用户注册相关接口")
@AllArgsConstructor
public class UserRegisterController {

    private final UserService userService;

    private final PasswordEncoder passwordEncoder;

    private final TokenStore tokenStore;

    private final PasswordManager passwordManager;

    public static String registerCode="registerCode:";

    private final SpringConfig springConfig;

    private final SendSmsService sendSmsService;

    @PostMapping("/register")
    @Operation(summary = "注册" , description = "用户注册或绑定手机号接口")
    public ServerResponseEntity<TokenInfoVO> register(@Valid @RequestBody UserRegisterParam userRegisterParam) {
        if (StrUtil.isBlank(userRegisterParam.getNickName())) {
            userRegisterParam.setNickName(userRegisterParam.getUserName());
        }
        // 正在进行申请注册
        if (userService.count(new LambdaQueryWrapper<User>().eq(User::getUserMobile, userRegisterParam.getMobile())) > 0) {
            // 该用户名已注册，无法重新注册
            throw new YamiShopBindException("该用户名已注册，无法重新注册");
        }

        User one = null;
        if(StringUtil.isNotBlank(userRegisterParam.getHigherLevelNickName())){
            one = userService.lambdaQuery().eq(User::getUserMobile, userRegisterParam.getHigherLevelNickName()).one();
            if(one == null){
                throw new YamiShopBindException("推荐人不存在");
            }
        }

        if(StringUtil.isBlank(userRegisterParam.getMobile())){
            throw new YamiShopBindException("用户手机号不能为空");
        }

        if(StringUtil.isBlank(userRegisterParam.getVerificationCode())){
            throw new YamiShopBindException("验证码不能为空");
        }

        //缓存的验证码
        String redisCode = (String)RedisUtil.get(registerCode + userRegisterParam.getMobile());

        if(StringUtils.isBlank(redisCode)){
            throw new YamiShopBindException("验证码已失效,请重新发送");
        }

        if(!StringUtils.equals(userRegisterParam.getVerificationCode(),redisCode)){
            throw new YamiShopBindException("验证码不正确");
        }

        //随机八位数
        String s =  RandomUtil.randomNumbers(8);

        Date now = new Date();
        User user = new User();
        user.setModifyTime(now);
        user.setUserRegtime(now);
        user.setStatus(1);
        user.setNickName(userRegisterParam.getNickName());
        user.setUserMail(userRegisterParam.getUserMail());
        String decryptPassword = passwordManager.decryptPassword(userRegisterParam.getPassWord());
        user.setLoginPassword(passwordEncoder.encode(decryptPassword));
        String userId = IdUtil.simpleUUID();
        user.setUserId(userId);

        user.setHigherLevelUid(one!=null?one.getUserId():null);//设置三级分销推荐人
        user.setSharedUid(one!=null?one.getUserId():null);//设置一级分销推荐人

        //设置用户的手机号,用于登录
        user.setUserMobile(userRegisterParam.getMobile());
        user.setMembershipCardNumber(s);

        userService.save(user);

        //重置推荐人等级失效时间
        if(one != null){
            //一个月之后
            DateTime offset = DateUtil.offset(new Date(), DateField.MONTH, 1);
            userService.lambdaUpdate().set(User::getUserLevelExpireDate,offset).eq(User::getUserId,one.getUserId()).update();
        }

        // 2. 登录
        UserInfoInTokenBO userInfoInTokenBO = new UserInfoInTokenBO();
        userInfoInTokenBO.setUserId(user.getUserId());
        userInfoInTokenBO.setSysType(SysTypeEnum.ORDINARY.value());
        userInfoInTokenBO.setIsAdmin(0);
        userInfoInTokenBO.setEnabled(true);
        return ServerResponseEntity.success(tokenStore.storeAndGetVo(userInfoInTokenBO));
    }

    @PostMapping("/sendRegisterCode")
    @Operation(summary = "发送注册验证码" , description = "发送注册验证码")
    public ServerResponseEntity<String> sendRegisterCode(String mobile) {
        if (!PrincipalUtil.isMobile(mobile)) {
            return ServerResponseEntity.showFailMsg("手机号码格式不正确");
        }
        //随机四位数
        String s =  RandomUtil.randomNumbers(4);

        String msg="";

        //发送验证码短信
        boolean prod = StringUtil.equals(springConfig.activeProfiles, "prod");
        if(prod){
            Map<String,String> map=new HashMap<>();
            map.put("code",s);

            //模板详情:您的验证码为：${code}，如非本人操作，请忽略本短信,5分钟内有效
            //https://dysms.console.aliyun.com/domestic/text/template
            sendSmsService.sendSms(mobile,"SMS_472795010",map);

            msg = "短信已发送";
        }else{
            msg = s;
        }

        //缓存验证码,三分钟失效
        RedisUtil.set(registerCode+mobile,s,5*60);
        return ServerResponseEntity.success(msg);
    }

   /* public static void main(String[] args) {
        String s = RandomUtil.randomNumbers(4);
        System.out.println(s);
    }*/
}
